<template>
    <s-layout id="layout" :title="'报销申请'" navbar="normal" leftIconColor="#ffffff" :autoBack="true"
        :bgColor="'rgba(0,0,0,0)'" :tabbarshow='false'
        :titleStyle="{ color: '#ffffff', fontSize: '32rpx', fontWeight: '600' }">
        <!-- 最大盒子 -->
        <view class="container" :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`, paddingTop: (safeAreaInsets?.top + 44) + 'px' }">
            <!-- 表单盒子 -->
            <view class="area form_box">
                <scroll-view scroll-y style="height: 66vh" :enable-back-to-top="true">
                    <u--form :labelStyle="labelStyle" labelPosition="left" :model="FormData" :rules="rules" ref="formRole" :borderBottom="false">
                        <!-- 报销类型 -->
                        <u-form-item @tap="selectiveType" required="true" :borderBottom="false" :labelWidth="100" label="报销类型：" prop="type" ref="type">
                            <u--input clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请选择" v-model="type_name" border="none"></u--input>
                        </u-form-item>
                        <!-- 回款信息 -->
                        <u-form-item @tap="returnedSwitch" required="true" :borderBottom="false" :labelWidth="100" label="回款信息：" prop="returned_id" ref="returned_id">
                            <u--input clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请选择" v-model="returned_title" border="none"></u--input>
                        </u-form-item>
                        <!-- 报销部门 -->
                        <u-form-item @tap="projectSwitch" v-if="FormData.type == 2 || FormData.type == 3" required="true" :borderBottom="false" :labelWidth="100" label="报销部门：" prop="department_id" ref="department_id">
                            <u--input clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请选择" v-model="project_title" border="none"></u--input>
                        </u-form-item>

                        <!-- 采购 -->
                        <u-form-item @tap="purchaseSwitch" v-if="FormData.type == 2" required="true" :borderBottom="false" :labelWidth="100" label="采购：" prop="purchase_id" ref="purchase_id">
                            <u--input clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请选择" v-model="purchase_title" border="none"></u--input>
                        </u-form-item>
                        <!-- 循环 -->
                        <view v-for="(item, index) of FormData.data" :key="index">
                            <!-- 报销明细盒子 -->
                            <view class="message">
                                报销明细{{ index + 1 }}
                                <view class="glide"></view>
                                <view class="delete" @tap="deleteFormData(index,item.price)" v-show="FormData.data.length != 1"> 移除</view>
                            </view>
                            <!-- 报销金额 -->
                            <u-form-item required="true" placeholder="请输入金额" :borderBottom="false" :labelWidth="120" label="报销金额(元)：" :prop="'data.' + index + '.price'" :ref="'data.' + index + '.price'"
                            :rules="rules[`data${index}.price`]">
                                <u--input @change="inputAddition" disabledColor="rgba(0,0,0,0)" inputAlign="right" type="digit" placeholder="请输入金额" v-model.trim="item.price" border="none"></u--input>
                            </u-form-item>
                            <!-- 费用发生日期 -->
                            <u-form-item required="true" :borderBottom="false" :labelWidth="120" label="费用发生日期：" prop="content" ref="content">
                                <view class="date_range" @tap="dateRange(index)">
                                    <view class="date_image">
                                        <image :src="`${baseUrl}/uploads/uniapp_image/staff/class_icon01.png`" mode="scaleToFill" />
                                    </view>
                                    <view class="range_time">{{ FormData.data[index].date ? FormData.data[index].date : '选择日期' }}</view>
                                    <view class="icon">
                                        <up-icon :bold="true" name="arrow-right" color="#0038F7" size="13"></up-icon>
                                    </view>
                                </view>
                            </u-form-item>
                            <!-- 报销内容 -->
                            <view>
                                <view class="remark"><text class="symbol">*</text>报销内容:</view>
                                <editor id="editor" class="ql-container" placeholder="请输入报销内容" @input="contentInput(index, $event)" @statuschange="onStatusChange"></editor>
                                <!-- <up-textarea
                                    :placeholderStyle="{ color: '#999999', fontWeight: 500, fontSize: '26rpx' }"
                                    height="80" v-model="item.content" placeholder="请输入报销内容"></up-textarea> -->
                            </view>
                            <!-- 备注 -->
                            <view>
                                <view class="remark">备注:</view>
                                <editor id="editor" class="ql-container" placeholder="请输入备注" @input="remarkInput(index, $event)" @statuschange="onStatusChange"></editor>
                                <!-- <up-textarea
                                    :placeholderStyle="{ color: '#999999', fontWeight: 500, fontSize: '26rpx' }"
                                    height="80" v-model="item.remark" placeholder="请输入备注"></up-textarea> -->
                            </view>
                            <!-- 发票 -->
                            <view>
                                <view class="image">发票:</view>
                                <u-upload :fileList="state[`fileList${index}`]" @afterRead="imageUpload" @delete="deletePic" :name="index" multiple :maxCount="10" :previewFullImage="true">
                                </u-upload>
                            </view>
                        </view>
                        <!-- 添加报销 -->
                        <view class="add_customer" @tap="addFormData">
                            + 添加报销
                        </view>
                    </u--form>
                </scroll-view>
            </view>
                <!-- 底部保存按钮 -->
                    
            <view class="fixed">
                <view class="fixed_bottom">
                    <!-- 报销总额 -->
                    <view class="total_reimbursement">报销总额(元)：</view>
                    <view class="money">{{ FormData.price_total ==  '' ? '0.00' : FormData.price_total }}</view>
                        <!-- <u--input clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="0.00" v-model="FormData.price_total" border="none"></u--input> -->
                </view>
                <view class="button_box">
                    <view class="button_item_box" @tap="submitForm">
                        <view class="turn_over">提交</view>
                    </view>
                </view>
                <view class="placeholder"></view>
            </view>    
        </view>
    </s-layout>

    <!-- 报销类型弹出框 -->
    <up-action-sheet :cancelText="'取消'" :actions="list" :title="type_title" :show="type_show" @close="type_close"
        @select="type_select"></up-action-sheet>
    <!-- 费用发生日期弹出框 -->
    <up-datetime-picker v-model="current_date" :closeOnClickOverlay="true" :show="date_show" @close="date_close" @confirm="date_confirm"
        @cancel="date_cancel" mode="date"></up-datetime-picker>
    <!-- 底部弹出组件 && 部门弹出 -->
    <s-project-class @selectedData="project_switchTitle" 
    :arrayList="projectDataList" ref="project_popupListRef"
    :searchBoxIsShow="false"   :showGoLink="false"></s-project-class>
    <!-- 底部弹出组件 && 回款账户弹出 -->
    <s-popup-list @selectedData="returned_switchTitle" :current_page="returned_current_page"
        :skipPage="'/subpackage/staff/workbench/returned_info/returned_info_add'"
        @subcomponentSearch="returned_subcomponentSearch" :last_page="returned_last_page"
        @pageEvent="returned_pageEvent" :arrayList="returnedDataList" ref="returned_popupListRef" :popupTitle="'选择银行卡'"
        :isBank="true" :listingName="'银行卡名称'" :searchBoxIsShow="false" :isPage="false" :showGoLink="'#'"></s-popup-list>
    <!-- 底部弹出组件 && 采购弹出 -->
    <s-popup-list :placeholder="'搜索采购信息'" @selectedData="purchase_switchTitle" :current_page="purchase_current_page"
        :last_page="purchase_last_page" @subcomponentSearch="purchase_subcomponentSearch"
        @pageEvent="purchase_pageEvent" :arrayList="purchaseDataList" ref="purchase_popupListRef" :popupTitle="'选择采购信息'"
        :listingName="'采购信息列表'" :showGoLink="'#'" :skipPage="'/subpackage/staff/workbench/purchase/purchase_add'"></s-popup-list>
</template>

<script setup>
import sheep from '@/sheep';
import { ref, reactive } from 'vue';
import { onLoad,onShow  } from '@dcloudio/uni-app';
import { baseUrl } from "@/sheep/config";
import { formatDate } from '@/utils/fn.js';
import { isEmpty } from '@/sheep/helper/utils.js'
const { safeAreaInsets } = uni.getSystemInfoSync()
onLoad(() => {
    let params={
            is_all:'1',
            is_include_main:'1'
        }
    projectList(params)           // 获取部门列表
    // purchaseIndexData()     // 获取采购列表
})
onShow(() => {
    // 回款
    returnedDataList.value = []
    returned_page.value = 1
    getReturnedInfoData()   // 获取回款账户列表
    // 采购
    purchaseDataList.value = []
    purchase_page.value = 1
    purchaseIndexData()     // 获取采购信息列表
})

const contentInput = (index,e) => {
    FormData.data[index].content = e.detail.html
}

const remarkInput = (index,e) => {
    FormData.data[index].remark = e.detail.html
}

const current_date = ref(Date.now());


const list = ref([
    { value: '1', name: '普通报销' },
    { value: '2', name: '采购报销' },
    { value: '3', name: '项目报销' },
])
const type_title = ref('请选择报销类型')
const type_show = ref(false)
const date_show = ref(false)

const FormData = reactive({
    type: '',            // 类型:1=普通报销,2=采购报销,3=部门报销
    purchase_id: '',     // 采购申请 ID，type 为 2 时必传
    returned_id: '',     // 回款信息 ID
    department_id: '',      // 部门ID，type 为 3时必传
    price_total: '',     // 总金额
    data: [{
        price: '',
        content: '',
        remark: '',
        date: '',
        images: ''
    }]             // json数据，各项申请数据
})

const rules = {
    type: [
        {
            required: true,
            message: '请选择报销类型',
        }
    ],
    purchase_id: [
        {
            validator: (rule, value, callback) => {
                if (FormData.type == '2' && value == '') {
                    callback(new Error('请选择采购信息'));
                } else {
                    callback();
                }
            },
            message: '请选择采购信息'
        }
    ],
    returned_id: [
        {
            required: true,
            message: '请选择回款信息',
        }
    ],
    department_id: [
        {
            validator: (rule, value, callback) => {
                if ((FormData.type == '2' || FormData.type == '3') && value == '') {
                    callback(new Error('请选择部门信息'));
                } else {
                    callback();
                }
            },
            message: '请选择部门信息'
        }
    ],
    price_total: [
        {
            required: true,
            message: '请输入报销金额',
        }
    ]
}

//获取部门列表
const projectDataList = ref([])
const project_title = ref('')
const project_popupListRef = ref(null)

// 点击弹出
const projectSwitch = () => {
    project_popupListRef.value.open()
}
// 封装部门列表接口
const projectList = async (params = null) => {
    const res = await sheep.$api.app.getDepartment(params);
    projectDataList.value = res.data;
};


// 拿过来的部门数据
const project_switchTitle = (item) => {
    project_title.value = item.jointTitles
    FormData.department_id = item.id
}

// 获取回款信息
const returnedDataList = ref([])
const returned_current_page = ref()
const returned_last_page = ref()
const returned_page = ref(1)
const returned_title = ref('')
const returned_popupListRef = ref(null)
const returned_keywords = ref()
// 点击弹出
const returnedSwitch = () => {
    returned_popupListRef.value.open()
}
// 封装回款账户接口
const getReturnedInfoData = async () => {
    let params = {
        filter: JSON.stringify({
            bank_name: returned_keywords.value,
            type: 'bank',
        }),
        op: JSON.stringify({
            bank_name: 'LIKE',
            type: '=',
        }),
        page: returned_page.value,
    };
    const res = await sheep.$api.returned_info.getReturnedInfo(params);
    returnedDataList.value = [...returnedDataList.value, ...res?.data.rows];
    // 改写数组
    returnedDataList.value.forEach(item => {
        let bank_number = item.bank_number.substr(0, 4) + '****' + item.bank_number.substr(-4)
        item.title = item.bank.name + '（' + bank_number + '）'
        item.logo = item.bank.logo
    });
    returned_current_page.value = res.data.current_page;
    returned_last_page.value = res.data.last_page;
}
// 回款账户列表分页
const returned_pageEvent = () => {
    if (returned_current_page.value < returned_last_page.value) {
        returned_page.value += 1;
    } else {
        return;
    }
    getReturnedInfoData();
}
// 回款信息搜索
const returned_subcomponentSearch = (value) => {
    returned_keywords.value = value
    returnedDataList.value = []
    returned_page.value = 1
    getReturnedInfoData();
}
// 拿过来的部门数据
const returned_switchTitle = (item) => {
    returned_title.value = item.title
    FormData.returned_id = item.id
}

// 获取采购列表
const purchaseDataList = ref([])
const purchase_current_page = ref()
const purchase_last_page = ref()
const purchase_page = ref(1)
const purchase_title = ref('')
const purchase_popupListRef = ref(null)
const purchase_keywords = ref()
// 点击弹出
const purchaseSwitch = () => {
    purchase_popupListRef.value.open()
}
// 封装采购列表接口
const purchaseIndexData = async () => {
    let params = {
        filter: JSON.stringify({
            title: purchase_keywords.value,
            state: '1'
        }),
        op: JSON.stringify({
            title: 'LIKE',
            state: '='
        }),
        page: purchase_page.value,
    };
    const res = await sheep.$api.purchase.getPurchaseIndex(params);
    purchaseDataList.value = [...purchaseDataList.value, ...res?.data.rows];
    purchase_current_page.value = res.data.current_page;
    purchase_last_page.value = res.data.last_page;
}
// 采购列表分页
const purchase_pageEvent = () => {
    if (purchase_current_page.value < purchase_last_page.value) {
        purchase_page.value += 1;
    } else {
        return;
    }
    purchaseIndexData();
}
// 采购列表搜索
const purchase_subcomponentSearch = (value) => {
    purchase_keywords.value = value
    purchaseDataList.value = []
    purchase_page.value = 1
    purchaseIndexData();
}
// 拿过来的部门数据
const purchase_switchTitle = (item) => {
    purchase_title.value = item.title
    FormData.purchase_id = item.id
}

// 总金额
const inputAddition = () => {
    let a = FormData.data.reduce((prev, next) => {
        return prev + Number(next.price);
    }, 0);
    FormData.price_total = a.toFixed(2);
}

// 增加报销明细表单
let annexlist = ref([
    []
]);
const addFormData = () => {
    if (FormData.data.length > 4) {
        uni.showToast({
            title: '一次仅能添加五组',
            icon: 'none',
            duration: 1000
        })
        return false
    }

    FormData.data.push({
        price: '',
        content: '',
        remark: '',
        date: '',
        images: ''
    });
    annexlist.value[FormData.data.length + 1] = [];
}

// 删除报销明细表单
const deleteFormData = (index,price) => {
    FormData.data.splice(index, 1)
    // rules.data.splice(index, 1)
    // FormData.price_total = Number(FormData.price_total) - Number(price)
    inputAddition()
}

// 选择类型
const type_name = ref('')
// 打开
const selectiveType = () => {
    type_show.value = true
}
// 关闭
const type_close = () => {
    type_show.value = false
}
// 选择
const type_select = (e) => {
    FormData.type = e.value
    type_name.value = e.name
    type_close()
}

// 选择费用发生日期
// 打开
const date_index = ref()
const dateRange = (index) => {
    date_show.value = true
    date_index.value = index
}
// 关闭
const date_close = () => {
    date_show.value = false
}
// 选择
const date_confirm = (e) => {
    FormData.data[date_index.value].date = formatDate(e.value / 1000)
    date_close()
}
// 取消
const date_cancel = () => {
    date_close()
}


// 保存提交
const formRole = ref(null)
const submitForm = () => {
    // #ifdef MP
        sheep.$platform.useProvider('wechat').subscribeMessage(['apply_notice','apply_result_notice']);
    // #endif
    uni.$u.throttle(() => {
    formRole.value.validate().then(async (res) => {
        for (const item of FormData.data) {
            if (isEmpty(item.price)) {
                await sheep.$helper.toast('请输入报销金额');
                return;
            }
            if (isEmpty(item.date)) {
                await sheep.$helper.toast('请选择费用发生日期');
                return;
            }
            if (isEmpty(item.content)) {
                await sheep.$helper.toast('请输入报销内容');
                return;
            }
        }
        const resust = await sheep.$api.reimburse.reimburseAddAPI(FormData);
        if (resust.code == 1) {
            sheep.$helper.toast(resust.msg);
            setTimeout(() => {
                sheep.$router.back(true)
            }, 500)
        } else {
            sheep.$helper.toast(resust.msg);
        }
    }).catch((err) => { })
},1000)
}

// 上传图片逻辑
const state = reactive({
    fileList0: [],
    fileList1: [],
    fileList2: [],
    fileList3: [],
    fileList4: [],
})

// 删除图片
const deletePic = (event) => {
    state[`fileList${event.name}`].splice(event.index, 1)
    let images = (FormData.data[event.name].images).split(',');
    images.splice(event.index, 1)
    FormData.data[event.name].images = images.join(',')
};

// 新增图片
const imageUpload = async (event) => {
    let lists = [].concat(event.file);
    let fileListLen = state[`fileList${event.name}`]?.length
    lists.map((item) => {
        state[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中',
        });
    });

    let uploadFile = [];
    for (let i = 0; i < lists.length; i++) {
        let { url } = await sheep.$api.app.upload(lists[i].url, 'ugc')
        uploadFile.push(url)
        let item = state[`fileList${event.name}`][fileListLen]
        state[`fileList${event.name}`].splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: sheep.$url.cdn(url),
        });
        fileListLen++;
    }
    if(FormData.data[event.name].images == '') {
            let a = uploadFile
            FormData.data[event.name].images = a.join(',')
        }else {
            let a = [FormData.data[event.name].images,...uploadFile]
            FormData.data[event.name].images = a.join(',')
        }
};

</script>

<style lang="scss" scoped>
// 文本编辑器样式
:deep(.ql-container) {
    padding: 30rpx 30rpx 0 30rpx;
    background-color: #f9faff;
     font-style: normal !important; /* 取消斜体 */
}
:deep(#editor) {
    font-style: normal !important; /* 取消斜体 */
}


:deep(.u-form-item__body.data-v-b4fd400b) {
    height: 80rpx;
    margin-bottom: 30rpx;
    padding-left: 10rpx;
    background-color: #F9FAFF;
}

:deep(.u-textarea.data-v-31706dd7) {
    background-color: #F9FAFF;
    padding: 0;
}

// uview 内部样式 button 按钮边框
:deep(.u-reset-button.data-v-05ea451b) {
    border-width: 0;
    height: 134rpx;
}

// uview 内部样式 up-textarea 文字距离
:deep(.u-textarea__field.data-v-31706dd7) {
    margin-top: 30rpx;
    margin-left: 30rpx;
}

// uview 内部样式 输入内容右边间距
:deep(.u-input__content__field-wrapper__field.data-v-5904192e) {
    margin-right: 20rpx;
}

// uview 内部样式 label左边间距
:deep(.u-form-item__body__left.data-v-b4fd400b) {
    margin-left: 20rpx;
}

// uview 内部样式 label字体粗细
:deep(.u-form-item__body__left__content__label.data-v-b4fd400b) {
    font-weight: $uni-font-weight;
}

// uview 内部样式 未输入提示拦截框
:deep(.u-form-item__body__right__message.data-v-b4fd400b) {
    margin-left: 0 !important;
}

// uview 内部样式 选择器弹窗
@import '../compentns/up_sheet.scss';

.fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
}

// 按钮集合大盒子
.button_box {
    background-color: #ffffff;
    height: 128rpx;
    width: 100%;
    justify-content: space-between;
    .button_item_box {
        padding: 18rpx 40rpx 20rpx 40rpx;
            // 选择移交按钮
        .turn_over {
            // width: 315rpx;
            height: 90rpx;
            border-radius: 45rpx;
            background-color: $uni-color-primary;
            font-family: PingFangSC;
            color: #ffffff;
            font-weight: $uni-font-weight;
            font-size: 34rpx;
            font-style: normal;
            text-decoration: none;
            text-align: center;
            line-height: 90rpx;
        }
    }
}

// 占位盒子
.placeholder {
    height: 32rpx;
    width: 100%;
    background-color: #ffffff;
}


// 最大盒子
.container {
    width: 100%;
    background-size: cover;
    /* 或 contain */
}

// 版心
.area {
    width: calc(100% - 40rpx);
    margin: 0 20rpx;
}

// 申请事由盒子
.form_box {
    width: calc(100% - 100rpx);
    padding: 60rpx 30rpx;
    margin-top: 20rpx;
    border-radius: 16rpx;
    background-color: #FFFFFF;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
    // position: relative;
}

// 报销明细
.message {
    display: flex;
    justify-content: space-between;
    /* 左右对齐 */
    width: 100%;
    height: 48rpx;
    margin: 30rpx 0;
    font-family: PingFangSC;
    color: $uni-text-color;
    font-weight: $uni-font-weight;
    font-size: 34rpx;
    font-style: normal;
    text-decoration: none;
    position: relative;
    align-items: center;

    .glide {
        width: 92rpx;
        height: 14rpx;
        border-radius: 5px;
        background-color: rgba(0, 56, 247, 0.5);
        position: absolute;
        bottom: 0;
        left: 20rpx;
        right: 0;
    }

    // 删除按钮
    .delete {
        font-family: PingFangSC;
        color: $uni-color-primary;
        font-weight: $uni-font-weight;
        font-size: $uni-font-size-sm;
        font-style: normal;
        text-decoration: none;
        text-align: left;
    }
}

// 报销内容
.remark {
    width: 100%;
    height: 100rpx;
    line-height: 100rpx;
    font-family: PingFangSC;
    color: $uni-text-color;
    font-weight: $uni-font-weight;
    font-size: 30rpx;
    font-style: normal;
    text-decoration: none;
}

// 图片
.image {
    width: 100%;
    height: 100rpx;
    line-height: 100rpx;
    font-family: PingFangSC;
    color: $uni-text-color;
    font-weight: $uni-font-weight;
    font-size: 30rpx;
    font-style: normal;
    text-decoration: none;
}

// 符号
.symbol {
    color: #f56c6c;
}

// 添加报销盒子
.add_customer {
    // width: 100%;
    height: 60rpx;
    border-radius: 16rpx;
    border: 2rpx solid $uni-color-primary;
    text-align: center;
    line-height: 60rpx;
    font-family: PingFangSC;
    color: $uni-color-primary;
    font-weight: $uni-font-weight;
    font-size: 22rpx;
    font-style: normal;
    text-decoration: none;
    margin: 30rpx 0;
}

// 选择日期盒子
.date_range {
    height: 64rpx;
    width: 274rpx;
    border-radius: 16rpx;
    border: 4rpx solid #1241E2;
    display: flex;
    align-items: center;
    margin-left: 13vw;
    position: relative;

    // 图片
    .date_image {
        width: 28rpx;
        height: 28rpx;
        margin-left: 20rpx;
        margin-right: 12rpx;

        image {
            width: 100%;
            height: 100%;
        }
    }
}

// 时间
.range_time {
    font-family: PingFangSC;
    color: $uni-color-primary;
    font-weight: $uni-font-weight;
   font-size:$uni-font-size-26;
    font-style: normal;
    text-decoration: none;
    text-align: right;
}

.icon {
    position: absolute;
    right: 30rpx;
}

// 总金额固定在底部
.fixed_bottom {
    padding-top: 10rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #ffffff;
    // margin-bottom: 70px;
}

// 报销总额
.total_reimbursement {
    font-family: PingFangSC;
    color: $uni-text-color;
    font-weight: $uni-font-weight;
    font-size: 30rpx;
    font-style: normal;
    text-decoration: none;
    margin-left: 30rpx;
}
// 金额样式
.money {
    font-family: PingFangSC;
    color: $uni-color-primary;
    font-weight: $uni-font-weight;
    font-size: 30rpx;
    font-style: normal;
    text-decoration: none;
    margin-right: 30rpx;
}
</style>
